from PyQt6.QtWidgets import (
    QWidget, QLabel, QDoubleSpinBox, QComboBox, QListWidget,
    QPushButton, QGroupBox, QFormLayout, QHBoxLayout, QVBoxLayout,
    QMessageBox, QTextEdit
)
from PyQt6.QtCore import Qt, pyqtSignal


class ParameterPanel(QWidget):
    """参数输入面板"""
    selection_changed = pyqtSignal(dict)
    pattern_confirmed = pyqtSignal(str, list)  # 图案确认信号

    def __init__(self, parent=None):
        super().__init__(parent)
        self.selected_modes = []  # 存储选中的拼摆方式
        self.init_ui()
        self.init_signals()

    def init_ui(self):
        """初始化用户界面"""
        # 主布局
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(15, 15, 15, 15)  # 修复了括号和参数
        main_layout.setSpacing(20)

        # ==== 场地尺寸分组 ====
        site_group = QGroupBox("场地尺寸 (米)")
        site_layout = QFormLayout(site_group)

        # 场地长度和宽度
        site_size_layout = QHBoxLayout()
        site_size_layout.addWidget(QLabel("长:"))
        self.site_length_input = QDoubleSpinBox()
        self.site_length_input.setRange(0, 1000)
        self.site_length_input.setSingleStep(0.5)
        self.site_length_input.setFixedWidth(100)
        site_size_layout.addWidget(self.site_length_input)

        site_size_layout.addWidget(QLabel("宽:"))
        self.site_width_input = QDoubleSpinBox()
        self.site_width_input.setRange(0, 1000)
        self.site_width_input.setSingleStep(0.5)
        self.site_width_input.setFixedWidth(100)
        site_size_layout.addWidget(self.site_width_input)

        site_container = QWidget()
        site_container.setLayout(site_size_layout)
        site_layout.addRow(QLabel("尺寸:"), site_container)

        main_layout.addWidget(site_group)

        # ==== 砖块尺寸分组 ====
        brick_group = QGroupBox("砖块尺寸 (米)")
        brick_layout = QFormLayout(brick_group)

        # 砖块长度、宽度和高度
        brick_size_layout = QHBoxLayout()
        brick_size_layout.addWidget(QLabel("长:"))
        self.brick_length_input = QDoubleSpinBox()
        self.brick_length_input.setRange(0.01, 10)
        self.brick_length_input.setSingleStep(0.01)
        self.brick_length_input.setFixedWidth(80)
        brick_size_layout.addWidget(self.brick_length_input)

        brick_size_layout.addWidget(QLabel("宽:"))
        self.brick_width_input = QDoubleSpinBox()
        self.brick_width_input.setRange(0.01, 10)
        self.brick_width_input.setSingle极强(0.01)
        self.brick_width_input.setFixedWidth(80)
        brick_size_layout.addWidget(self.brick_width_input)

        brick_size_layout.addWidget(QLabel("高:"))
        self.brick_height_input = QDoubleSpinBox()
        self.brick_height_input.setRange(0.01, 5)
        self.brick_height_input.setSingleStep(0.01)
        self.brick_height_input.setFixedWidth(80)
        brick_size_layout.addWidget(self.brick_height_input)

        brick_container = QWidget()
        brick_container.setLayout(brick_size_layout)
        brick_layout.addRow(QLabel("尺寸:"), brick_container)

        main_layout.addWidget(brick_group)

        # ==== 单价设置分组 ====
        price_group = QGroupBox("单价设置")
        price_layout = QFormLayout(price_group)

        # 第一行单价
        price_row1_layout = QHBoxLayout()
        price_row1_layout.addWidget(QLabel("砖块单价:"))
        self.brick_price_input = QDoubleSpinBox()
        self.brick_price_input.setRange(0, 1000)
        self.brick_price_input.setSingleStep(0.1)
        self.brick_price_input.setFixedWidth(100)
        price_row1_layout.addWidget(self.brick_price_input)
        price_row1_layout.addWidget(QLabel("元/块"))

        price_row1_layout.addWidget(QLabel("砂单价:"))
        self.sand_price_input = QDoubleSpinBox()
        self.sand_price_input.setRange(0, 1000)
        self.sand_price_input.setSingleStep(0.1)
        self.sand_price_input.setFixedWidth(100)
        price_row1_layout.addWidget(self.sand_price_input)
        price_row1_layout.addWidget(QLabel("元/立方米"))

        price_row1_container = QWidget()
        price_row1_container.setLayout(price_row1_layout)
        price_layout.addRow(QLabel(""), price_row1_container)

        # 第二行单价
        price_row2_layout = QHBoxLayout()
        price_row2_layout.addWidget(QLabel("人工单价:"))
        self.labor_price_input = QDoubleSpinBox()
        self.labor_price_input.setRange(0, 1000)
        self.labor_price_input.setSingleStep(0.1)
        self.labor_price_input.setFixedWidth(100)
        price_row2_layout.addWidget(self.labor_price_input)
        price_row2_layout.addWidget(QLabel("元/平方米"))

        price_row2_layout.addWidget(QLabel("石单价:"))
        self.stone_price_input = QDoubleSpinBox()
        self.stone_price_input.setRange(0, 1000)
        self.stone_price_input.setSingleStep(0.1)
        self.stone_price_input.setFixedWidth(100)
        price_row2_layout.addWidget(self.stone_price_input)
        price_row2_layout.addWidget(QLabel("元/立方"))

        price_row2_container = QWidget()
        price_row2_container.setLayout(price_row2_layout)
        price_layout.addRow(QLabel(""), price_row2_container)

        # 第三行单价
        price_row3_layout = QHBoxLayout()
        price_row3_layout.addWidget(QLabel("水泥单价:"))
        self.cement_price_input = QDoubleSpinBox()
        self.cement_price_input.setRange(0, 1000)
        self.cement_price_input.setSingleStep(0.1)
        self.cement_price_input.setFixedWidth(100)
        price_row3_layout.addWidget(self.cement_price_input)
        price_row3_layout.addWidget(QLabel("元/吨"))

        price_row3_layout.addWidget(QLabel("水泥砂浆:"))
        self.mortar_price_input = QDoubleSpinBox()
        self.mortar_price_input.setRange(0, 1000)
        self.mortar_price_input.setSingleStep(0.1)
        self.mortar_price_input.setFixedWidth(100)
        price_row3_layout.addWidget(self.mortar_price_input)
        price_row3_layout.addWidget(QLabel("元/平方"))

        price_row3_container = QWidget()
        price_row3_container.setLayout(price_row3_layout)
        price_layout.addRow(QLabel(""), price_row3_container)

        main_layout.addWidget(price_group)

        # ==== 图案类型和拼摆方式分组 ====
        pattern_group = QGroupBox("图案与拼摆")
        pattern_layout = QFormLayout(pattern_group)

        # 图案类型选择
        pattern_layout.addRow(QLabel("图案类型:"), self.create_pattern_combo())

        # 拼摆方式选择
        pattern_layout.addRow(QLabel("拼摆方式:"), self.create_modes_combo())

        # 确定按钮
        self.confirm_button = QPushButton("确定生成图案")
        pattern_layout.addRow(QLabel(""), self.confirm_button)

        main_layout.addWidget(pattern_group)

        # ==== 材料数量计算分组 ====
        material_group = QGroupBox("材料数量计算")
        material_layout = QVBoxLayout(material_group)

        self.material_calculation_text = QTextEdit()
        self.material_calculation_text.setPlaceholderText("材料数量计算结果将在这里显示")
        self.material_calculation_text.setMaximumHeight(100)
        material_layout.addWidget(self.material_calculation_text)

        main_layout.addWidget(material_group)

        # ==== 总成本计算分组 ====
        cost_group = QGroupBox("总成本计算")
        cost_layout = QVBoxLayout(cost_group)

        self.total_cost_text = QTextEdit()
        self.total_cost_text.setPlaceholderText("总成本计算结果将在这里显示")
        self.total_cost_text.setMaximumHeight(100)
        cost_layout.addWidget(self.total_cost_text)

        main_layout.addWidget(cost_group)

        # ==== 技术要领分组 ====
        technique_group = QGroupBox("拼摆图案技术要领")
        technique_layout = QVBoxLayout(technique_group)

        self.technique_text = QTextEdit()
        self.technique_text.setPlaceholderText("技术要领说明将在这里显示")
        self.technique_text.setMaximumHeight(100)
        technique_layout.addWidget(self.technique_text)

        main_layout.addWidget(technique_group)

        # ==== 操作步骤分组 ====
        steps_group = QGroupBox("图案拼摆操作步骤说明")
        steps_layout = QVBoxLayout(steps_group)

        self.steps_text = QTextEdit()
        self.steps_text.setPlaceholderText("操作步骤说明将在这里显示")
        self.steps_text.setMaximumHeight(100)
        steps_layout.addWidget(self.steps_text)

        main_layout.addWidget(steps_group)

    def create_pattern_combo(self):
        """创建图案类型选择框"""
        self.pattern_combo = QComboBox()
        self.pattern_combo.addItems([
            "默认方形", "圆形阵列", "线性排列", "菱形网格",
            "波浪形", "星形", "十字形", "菱形", "梯形",
            "椭圆形", "心形", "六边形蜂窝", "三角形阵列", "单拼基底"
        ])
        return self.pattern_combo

    def create_modes_combo(self):
        """创建拼摆方式选择框"""
        modes_layout = QHBoxLayout()

        self.modes_combo = QComboBox()
        self.modes_combo.addItems(["单拼", "双拼", "三拼", "四拼", "交错拼", "对缝拼", "斜拼"])
        modes_layout.addWidget(self.modes_combo)

        self.selected_modes_label = QLabel("已选择: 无")
        modes_layout.addWidget(self.selected_modes_label)

        container = QWidget()
        container.setLayout(modes_layout)
        return container

    def init_signals(self):
        """初始化信号连接"""
        # 确定按钮点击事件
        self.confirm_button.clicked.connect(self.on_confirm)

        # 拼摆方式选择变化
        self.modes_combo.currentTextChanged.connect(self.update_selected_modes)

        # 输入变化触发计算
        for spinbox in [
            self.site_length_input, self.site_width_input,
            self.brick_length_input, self.brick_width_input, self.brick_height_input,
            self.brick_price_input, self.sand_price_input, self.labor_price_input,
            self.stone_price_input, self.cement_price_input, self.mortar_price_input
        ]:
            spinbox.valueChanged.connect(self.calculate_all)

    def update_selected_modes(self):
        """更新已选择的拼摆方式"""
        selected_mode = self.modes_combo.currentText()
        if selected_mode and selected_mode not in self.selected_modes:
            if len(self.selected_modes) < 4:
                self.selected_modes.append(selected_mode)
                self.selected_modes_label.setText(f"已选择: {'+'.join(self.selected_modes)}")
            else:
                QMessageBox.information(self, "提示", "最多只能选择4种拼摆方式")

    def on_confirm(self):
        """处理确定按钮点击事件"""
        if not self.selected_modes:
            QMessageBox.warning(self, "提示", "请选择至少一种拼摆方式")
            return

        # 获取图案类型
        pattern_type = self.pattern_combo.currentText()

        # 发出信号
        self.pattern_confirmed.emit(pattern_type, self.selected_modes)

        # 更新显示
        self.update_displays(pattern_type, self.selected_modes)

    def calculate_all(self):
        """计算材料用量和总成本"""
        try:
            # 获取场地尺寸
            site_length = self.site_length_input.value()
            site_width = self.site_width_input.value()
            site_area = site_length * site_width

            # 检查场地尺寸
            if site_area <= 0:
                raise ValueError("场地尺寸必须大于0")

            # 获取砖块尺寸
            brick_length = self.brick_length_input.value()
            brick_width = self.brick_width_input.value()
            brick_height = self.brick_height_input.value()

            # 检查砖块尺寸
            if brick_length <= 0 or brick_width <= 0 or brick_height <= 0:
                raise ValueError("砖块尺寸必须大于0")

            # 计算砖块数量
            brick_count = site_area / (brick_length * brick_width)

            # 计算材料用量
            cement_usage = site_area * 0.2  # 假设每平米需要0.2吨水泥
            sand_usage = site_area * 0.5  # 假设每平米需要0.5立方米砂
            stone_usage = site_area * 0.3  # 假设每平米需要0.3立方米石

            # 获取单价
            brick_price = self.brick_price_input.value()
            sand_price = self.sand_price_input.value()
            labor_price = self.labor_price_input.value()
            stone_price = self.stone_price_input.value()
            cement_price = self.cement_price_input.value()
            mortar_price = self.mortar_price_input.value()

            # 计算成本
            brick_cost = brick_count * brick_price
            sand_cost = sand_usage * sand_price
            labor_cost = site_area * labor_price
            stone_cost = stone_usage * stone_price
            cement_cost = cement_usage * cement_price
            mortar_cost = site_area * mortar_price

            total_cost = brick_cost + sand_cost + labor_cost + stone_cost + cement_cost + mortar_cost

            # 更新材料计算显示
            material_text = f"""
            砖块数量: {brick_count:.0f} 块
            水泥用量: {cement_usage:.2f} 吨
            砂用量: {sand_usage:.2f} 立方米
            石用量: {stone_usage:.2f} 立方米
            """
            self.material_calculation_text.setText(material_text)

            # 更新总成本显示
            cost_text = f"""
            总成本: {total_cost:.2f} 元
            砖块成本: {brick_cost:.2f} 元
            人工成本: {labor_cost:.2f} 元
            材料成本: {sand_cost + stone_cost + cement_cost + mortar_cost:.2f} 元
            """
            self.total_cost_text.setText(cost_text)

        except Exception as e:
            self.material_calculation_text.setText(f"计算错误: {str(e)}")
            self.total_cost_text.setText("请检查输入参数")

    def update_displays(self, pattern_type, selected_modes):
        """更新技术要领和操作步骤显示"""
        try:
            # 生成技术要领
            technique_text = f"""
            图案类型: {pattern_type}
            拼摆方式: {'+'.join(selected_modes)}

            技术要领:
            1. 确保基础平整牢固
            2. 按照{pattern_type}图案进行布局
            3. 使用{selected_modes[0]}作为主要拼摆方式
            4. 注意砖块之间的缝隙保持一致
            5. 从中心向四周铺设，确保整体对称
            """
            self.technique_text.setText(technique_text)

            # 生成操作步骤
            steps_text = f"""
            操作步骤:
            1. 测量场地尺寸: {self.site_length_input.value()}m × {self.site_width_input.value()}m
            2. 准备砖块: 长={self.brick_length_input.value()}m, 宽={self.brick_width_input.value()}m, 高={self.brick_height_input.value()}m
            3. 按照{pattern_type}图案进行布局
            4. 采用{'+'.join(selected_modes)}拼摆方式
            5. 从中心向四周铺设
            6. 定期检查平整度和对齐度
            7. 完成铺设后进行整体检查
            """
            self.steps_text.setText(steps_text)
        except Exception as e:
            self.technique_text.setText(f"生成技术要领出错: {str(e)}")
            self.steps_text.setText("生成操作步骤出错")